package com.wsfk.ssm.tools;

import java.util.Date;
import java.util.Random;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class RandomString {

	public static String randomString(String str) {

		str += new Date().getTime();
		StringBuffer result = new StringBuffer();
		int length = str.length();
		char[] chars = str.toCharArray();
		// 数组下标
		int index = -1;
		while (true) {
			// 随机 生成 下标
			index = new Random().nextInt(length);
			// 是否为空
			if (chars[index] != ' ') {
				result.append(chars[index]);
				// 全部获取完毕
				if (result.length() == length) {
					break;
				}
				// 置空
				chars[index] = ' ';
			} else
				continue;
		}
		return result.toString();
	}

	// 生成一个随机字符串
	public static String randomNumber() {
		String val = "";
		Random random = new Random();
		for (int i = 0; i < 8; i++) {
			String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; // 输出字母还是数字
			if ("char".equalsIgnoreCase(charOrNum)) // 字符串
			{
				int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; // 取得大写字母还是小写字母
				val += (char) (choice + random.nextInt(26));
			} else if ("num".equalsIgnoreCase(charOrNum)) // 数字
			{
				val += String.valueOf(random.nextInt(10));
			}
		}
		return val;
	}

	//MD5加密码
	public static String encryption(String str){
		
		MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            
            e.printStackTrace();
        }
        md.update(str.getBytes());
        /** ascii */
        byte[] encodedPassword = md.digest();

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < encodedPassword.length; i++) {
            
            if ((encodedPassword[i] & 0xff) < 0x10)
            {
                sb.append("0");
            }
            sb.append(Long.toString(encodedPassword[i] & 0xff, 16));
        }
        
		return sb.toString();
	}
}
